'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.REQUEST_ERROR_TYPE = undefined;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _request = require('../../utils/request');

var _request2 = _interopRequireDefault(_request);

var _CALL_API = require('./CALL_API');

var _CALL_API2 = _interopRequireDefault(_CALL_API);

var _validation = require('./validation');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { return step("next", value); }, function (err) { return step("throw", err); }); } } return step("next"); }); }; }
// import { Schema, arrayOf, normalize } from 'normalizr'


var REQUEST_ERROR_TYPE = exports.REQUEST_ERROR_TYPE = "REQUEST_ERROR_TYPE";
// 在RSAA上额外添加一个headers
// A Redux middleware that interprets actions with CALL_API info specified.
// Performs the call and promises when such actions are dispatched.

exports.default = function (store) {
  return function (next) {
    return function () {
      var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(action) {
        var callAPI, endpoint, method, body, credentials, bailout, types, headers, meta, actionWith, _types, requestType, successType, failureType;

        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                actionWith = function actionWith(data) {
                  var finalAction = _extends({}, action, data);
                  delete finalAction[_CALL_API2.default];
                  return finalAction;
                };

                callAPI = action[_CALL_API2.default];

                // Do not process actions without a [CALL_API] property

                if ((0, _validation.isRSAA)(action)) {
                  _context.next = 4;
                  break;
                }

                return _context.abrupt('return', next(action));

              case 4:
                endpoint = callAPI.endpoint;
                // const { schema, types } = callAPI

                method = callAPI.method;
                body = callAPI.body;
                credentials = callAPI.credentials;
                bailout = callAPI.bailout;
                types = callAPI.types;
                headers = callAPI.headers;
                meta = callAPI.meta;


                if (typeof endpoint === 'function') {
                  endpoint = endpoint(store.getState());
                }

                if (!(typeof endpoint !== 'string')) {
                  _context.next = 15;
                  break;
                }

                throw new Error('Specify a string endpoint URL.');

              case 15:
                if (!(!Array.isArray(types) || types.length !== 3)) {
                  _context.next = 17;
                  break;
                }

                throw new Error('Expected an array of three action types.');

              case 17:
                if (types.every(function (type) {
                  return typeof type === 'string';
                })) {
                  _context.next = 19;
                  break;
                }

                throw new Error('Expected action types to be strings.');

              case 19:
                _types = _slicedToArray(types, 3);
                requestType = _types[0];
                successType = _types[1];
                failureType = _types[2];

                next(actionWith({ type: requestType }));

                //修改,使用payload把data包起来, 把RSAA的body转成data
                return _context.abrupt('return', (0, _request2.default)(endpoint, _extends({ method: method, data: body, credentials: credentials, types: types }, headers)).then(function (response) {
                  return next(actionWith({
                    payload: response.payload ? response.payload : response,
                    meta: meta,
                    type: successType
                  }));
                }, function (error) {
                  next({ type: REQUEST_ERROR_TYPE, status: error.status });
                  next(actionWith({
                    type: failureType,
                    error: error.message || 'Something bad happened'
                  }));
                }));

              case 25:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, undefined);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }();
  };
};